package edu.cmu.pocketsphinx.demo;

import java.util.Date;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;



public class SpeechCall extends Activity implements OnTouchListener, RecognitionListener {
	
	//********************************************************//
	//khai bao cac views su dung trong main chinh
	Button button1, button2, button3, Rec; 
    Button button4, button5, button6; ImageButton imgbtDelete;
    Button button7, button8, button9; ImageButton imgbtClear;
    Button button0; ImageButton imgbtCall;
    
    TextView numberView;
    //********************************************************//
	
	static {
		System.loadLibrary("pocketsphinx_jni");
	}
	/**
	 * Recognizer task, which runs in a worker thread.
	 */
	RecognizerTask rec;
	/**
	 * Thread in which the recognizer task runs.
	 */
	Thread rec_thread;
	/**
	 * Time at which current recognition started.
	 */
	Date start_date;
	/**
	 * Number of seconds of speech.
	 */
	float speech_dur;
	/**
	 * Are we listening?
	 */
	boolean listening;
	/**
	 * Progress dialog for final recognition.
	 */
	ProgressDialog rec_dialog;
	/**
	 * Performance counter view.
	 */
	TextView performance_text;
	/**
	 * Editable text view.
	 */
	TextView edit_text;
	
	/**
	 * Respond to touch events on the Speak button.
	 * 
	 * This allows the Speak button to function as a "push and hold" button, by
	 * triggering the start of recognition when it is first pushed, and the end
	 * of recognition when it is released.
	 * 
	 * @param v
	 *            View on which this event is called
	 * @param event
	 *            Event that was triggered.
	 */
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			start_date = new Date();
			this.listening = true;
			this.rec.start();
			break;
		case MotionEvent.ACTION_UP:
			Date end_date = new Date();
			long nmsec = end_date.getTime() - start_date.getTime();
			this.speech_dur = (float)nmsec / 1000;
			if (this.listening) {
				Log.d(getClass().getName(), "Showing Dialog");
				this.rec_dialog = ProgressDialog.show(SpeechCall.this, "", "Đang nhận dạng...", true);
				this.rec_dialog.setCancelable(false);
				this.listening = false;
			}			
			this.rec.stop();			
			break;
		default:
			;
		}
		/* Let the button handle its own state */
		return false;
	}

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		 //********************************************************//
        //lay ve cac views phuc vu cho chuong trinh
        numberView = (TextView) findViewById(R.id.NumberView);
        
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3); 
        
        button4 = (Button) findViewById(R.id.button4);        
        button5 = (Button) findViewById(R.id.button5);
        button6 = (Button) findViewById(R.id.button6);  
        imgbtDelete = (ImageButton) findViewById(R.id.imageButtonDelete);
         
        button7 = (Button) findViewById(R.id.button7);
        button8 = (Button) findViewById(R.id.button8);        
        button9 = (Button) findViewById(R.id.button9); 
        imgbtClear = (ImageButton) findViewById(R.id.imageButtonClear);
        
        button0 = (Button) findViewById(R.id.button0);        
        imgbtCall = (ImageButton) findViewById(R.id.imageButtonCall);
      //********************************************************//   
        
        
      //********************************************************//
        //set listener cho cac button hien thi
        button1.setOnClickListener(this.onclickView("1"));
        button2.setOnClickListener(this.onclickView("2"));
        button3.setOnClickListener(this.onclickView("3"));        
        button4.setOnClickListener(this.onclickView("4"));
        button5.setOnClickListener(this.onclickView("5"));
        button6.setOnClickListener(this.onclickView("6"));        
        button7.setOnClickListener(this.onclickView("7"));
        button8.setOnClickListener(this.onclickView("8"));
        button9.setOnClickListener(this.onclickView("9"));        
        button0.setOnClickListener(this.onclickView("0"));
      //********************************************************//
        
      //tao su kien xoa numberview khi click imgbtclear
        imgbtClear.setOnClickListener(this.onclickView("clear"));
        
      //tao su kien delete text trong numberview khi click imgbtclear
        imgbtDelete.setOnClickListener(this.onclickView("del"));		
        
      //tao su kien khi click imgbtcall de thuc hien cuoc goi.    
        imgbtCall.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:"+numberView.getText()));
				startActivity(intent);
			}
		});
        
    //********************************************************//
    //record and regconize speech 	
		this.rec = new RecognizerTask();			//lay ve 1 doi tuong RecognizeTask
		this.rec_thread = new Thread(this.rec);		//tao luong^- moi cho record
		this.listening = false;						//setup gia tri cho bien bool listening = false
		Rec = (Button) findViewById(R.id.ButtonRecord);	//lấy về Button Rec.
		Rec.setOnTouchListener(this);					//tao su kien cho button rec
		
		this.performance_text = (TextView) findViewById(R.id.PerformanceText);  //lay ve textview hien thi thong so sau khi record
		this.edit_text = (TextView) findViewById(R.id.NumberView);				//lay ve textview hien thi so duoc nhan dang
		this.rec.setRecognitionListener(this);
		this.rec_thread.start();
	//********************************************************//		
	} //dong het than chuong trinh chinh
	
	//********************************************************//
    //phuong thuc hien thi text len text view khi nhan 1 phim so, xóa textview, delete number
    public OnClickListener onclickView(final String choice) {
    	return new OnClickListener() {
			public void onClick(View arg0) {
				if(choice == "clear")
				{
					numberView.setText("");
				}
				else
				{
					if(choice == "del")
					{
						if(numberView.length() > 0)
						{
							String s = numberView.getText().toString();
							s = s.substring(0,s.length()-1);
							numberView.setText(s);
						}
					}
					else 
					{
						numberView.append(choice);
					}
				}
			}    		
    	};
    }
  //********************************************************//
	
	//********************************************************//
    //phuong thuc khoi tao menu exit khi nhan phim menu tren dien thoai
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	menu.add(0, Menu.FIRST, 0,"Exit" ).setIcon(android.R.drawable.ic_delete);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    		case Menu.FIRST: {
    			finish();
    			break;
    		}
    	}
    	return false;
    }
  //********************************************************//

	/** phuong thuc hien thi ket qua tung phan duoc nhan dang */
	public void onPartialResults(Bundle b) {
		final SpeechCall that = this;
		final String hyp = b.getString("hyp");
		that.edit_text.post(new Runnable() {
			public void run() {
				that.edit_text.setText(hyp);
			}
		});
	}

	/** phuong thuc hien thi ket qua nhan dang cuoi cung */
	public void onResults(Bundle b) {
		final String hyp = b.getString("hyp");
		final SpeechCall that = this;
		this.edit_text.post(new Runnable() {
			public void run() {
				that.edit_text.setText(hyp);
				Date end_date = new Date();
				long nmsec = end_date.getTime() - that.start_date.getTime();
				float rec_dur = (float)nmsec / 1000;
				that.performance_text.setText(String.format("%.2f seconds %.2f xRT",
															that.speech_dur,
															rec_dur / that.speech_dur));
				Log.d(getClass().getName(), "Hiding Dialog");
				that.rec_dialog.dismiss(); //den day la da ra ket qua nhan dang roi
				
				//tach bo dau " " ra khoi chuoi nhan dang
				String rs = edit_text.getText().toString();
				
				StringTokenizer rs1 = new StringTokenizer(rs," ");
				String fin = "";
				while(rs1.hasMoreTokens())
				{
					fin = fin+rs1.nextToken();
				}
				edit_text.setText(fin);
				/////////////////////////////////////
			}
		});
	}

	public void onError(int err) {
		final SpeechCall that = this;
		that.edit_text.post(new Runnable() {
			public void run() {
				that.rec_dialog.dismiss();
			}
		});
	}
}